package leecode

import "container/list"

func deepestLeavesSum(root *TreeNode) int {
	if root == nil {
		return 0
	}
	var result [][]int
	queue := list.New()
	queue.PushBack(root)
	for queue.Len() != 0 {
		temp := make([]int, 0)
		size := queue.Len()
		for i := 0; i < size; i++ {
			node := queue.Remove(queue.Front()).(*TreeNode)
			if node.Left != nil {
				queue.PushBack(node.Left)
			}
			if node.Right != nil {
				queue.PushBack(node.Right)
			}
			temp = append(temp, node.Val)
		}
		result = append(result, temp)
	}
	var sum int
	for j := 0; j < len(result[len(result)-1]); j++ {
		sum += result[len(result)-1][j]
	}
	return sum
}
